package com.tsx.response.handler;

import com.tsx.response.entity.result.R;
import com.tsx.response.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BizException.class)
//    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public R<String> bizException(BizException bizException) {
        String path = getPath();
        log.error("BizException:{} path:{}", bizException.getMessage(), path, bizException);
        return R.error(bizException.getCode(), bizException.getMessage());
    }

    public String getPath() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            return servletRequestAttributes.getRequest().getRequestURI();
        }
        return "";
    }
}
